package com.starhub.base.license.utils;

import java.io.BufferedReader;  
import java.io.FileReader;  
import java.io.StringWriter;  
import java.nio.charset.StandardCharsets;  
import java.security.KeyFactory;  
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;  

/**
 * 加载私钥
 */
public class KeyUtil {  
    public static PrivateKey loadPrivateKey(String privateKeyPath) throws Exception {  
        // 从文件中读取私钥  
        BufferedReader reader = new BufferedReader(new FileReader(privateKeyPath));  
        StringWriter keyBuilder = new StringWriter();  
        String line;  

        // 忽略文件头和尾的标记行  
        while ((line = reader.readLine()) != null) {  
            if (line.contains("-----BEGIN PRIVATE KEY-----") || line.contains("-----END PRIVATE KEY-----")) {  
                continue;  
            }  
            keyBuilder.write(line);  
        }  
        reader.close();  

        // Base64 解码密钥内容  
        byte[] keyBytes = Base64.getDecoder().decode(keyBuilder.toString());  

        // 使用 PKCS8 格式解析私钥  
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);  
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");  
        return keyFactory.generatePrivate(keySpec);  
    }  


    /**  
     * 从文件加载公钥（PEM 格式）  
     * @param publicKeyPath 公钥文件路径  
     * @return PublicKey 实例  
     * @throws Exception 如果解析公钥失败，抛出异常  
     */  
    public static PublicKey loadPublicKey(String publicKeyPath) throws Exception {  
        // 读取公钥文件内容  
        BufferedReader reader = new BufferedReader(new FileReader(publicKeyPath));  
        StringWriter keyBuilder = new StringWriter();  
        String line;  

        // 跳过包含 "-----BEGIN PUBLIC KEY-----" 和 "-----END PUBLIC KEY-----" 的行  
        while ((line = reader.readLine()) != null) {  
            if (line.contains("-----BEGIN PUBLIC KEY-----") || line.contains("-----END PUBLIC KEY-----")) {  
                continue;  
            }  
            keyBuilder.write(line.trim()); // 去掉每行多余的空格  
        }  
        reader.close();  

        // 解码 Base64 编码的公钥内容  
        byte[] keyBytes = Base64.getDecoder().decode(keyBuilder.toString());  

        // 创建 X.509 格式的公钥规格  
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);  

        // 生成公钥实例  
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");  
        return keyFactory.generatePublic(keySpec);  
    }
}
